﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessObjects.BO_GetObjects;
using DigiLib;
using System.Data;
using System.Data.SqlTypes;

public partial class Administrator_Controls_AddNewGroupUser : System.Web.UI.UserControl {
    private DataTable objDT = null;
    private string result = string.Empty;

    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            LoadData();
        }
    }

    protected void LoadData() {

        #region Load groups
        ddlParentGroup.DataTextField = "GROUP_NAME";
        ddlParentGroup.DataValueField = "GROUP_USER_ID";
        ddlParentGroup.DataSource = BO_cms_group_users.GetByParentID(0);
        ddlParentGroup.DataBind();
        #endregion

        #region Load all permission
        objDT = BO_cms_admin_modules.Inside(0);
        lstPermission.Items.Clear();
        foreach (DataRow dr in objDT.Rows) {
            lstPermission.Items.Add(new ListItem(dr["DESCRIPTION"].ToString(), dr["ADMIN_MODULE_ID"].ToString()));
        }
        #endregion
    }

    protected void btnSubmit_Click(object sender, EventArgs e) {
        try {
            int parent_id = Convert.ToInt32(ddlParentGroup.SelectedValue);
            int next_order = SqlUtils.GetNextOrderDisplay("cms_group_users");

            #region Insert new group users
            result = BO_cms_group_users.Insert(parent_id
                , txtGroupName.Text.Trim()
                , txtDesc.Text.Trim()
                , SqlDateTime.Null
                , string.Empty
                , string.Empty
                , SqlDateTime.Null
                , string.Empty
                , string.Empty
                , next_order
                , DateTime.Now
                , Administrator.USER_NAME
                , SqlDateTime.Null
                , string.Empty
                , true
                , false);
            #endregion

            #region Grant Permission
            var selectedItems = lstPermission.Items.GetSelectedItems();
            if (selectedItems.Count() > 0) {
                foreach (ListItem item in selectedItems) {
                    BO_cms_groups_in_roles.Insert(Convert.ToInt32(result), Convert.ToInt32(item.Value));
                }
            }
            #endregion

            divMessage.InnerHtml = MessageBox.Success("Thông báo", "Thêm nhóm quản trị viên thành công!");
        } catch (Exception ex) {
            divMessage.InnerHtml = MessageBox.Error("Lỗi", "Phát hiện lỗi sau: " + ex.Message);
        }
    }
}
